"""
main power used an old PC'atx power board
"""
import uasyncio as asyncio
from machine import Pin, UART
from ZK6522C import ZK6522C, ZK6522C_STATUS, ZK6522C_PRESETS
class Main_Power:

    def __init__(self, power_ctl, power_tx, power_rx, status_data_callback):
        print("-" * 36)
        print("init Current Monitor...")
        self.power_status = False
        self.power_ctl = Pin(power_ctl, Pin.OUT)
        self.power_ctl.value(0)
        self.presets = []
        self.data_callback = status_data_callback
        self.uart = self._init_uart(power_tx, power_rx)
        self.zk6522c = self._init_zk6522c(self.uart)
        asyncio.create_task(self.loop_read_data())
        print("-" * 36)


    def _init_uart(self, power_tx, power_rx):
        uart = None
        try:
            uart = UART(1, baudrate=115200, tx=Pin(power_tx), rx=Pin(power_rx))
            #asyncio.create_task(self.uart_reader())
        except Exception as e:
            print("MainPower._init_uart failed:", e)
        return uart

    def _init_zk6522c(self, uart):
        dev = None
        try:
            dev = ZK6522C(uart)
            for i in range(0, 12):
                rsv = dev.sendcmd_Read_SaveData(0)
                print("read presets ", i, " data---->:\n", rsv)
                preset = ZK6522C_PRESETS(rsv)
                self.presets.append(preset)
                preset.show_status()
            
        except  Exception as e:
            print("MainPower._init_zk6522c failed:", e)
        return dev

      

    async def loop_read_data(self):
        while True:
            #print("UartLcd.uart_reader...")
            try:
                rsv = self.zk6522c.sendcmd_Read_Status()
                st = ZK6522C_STATUS(rsv)
#                 st.show_status()
                if self.data_callback:
                    self.data_callback(st)
            except Exception as e:
                print("loop read ZK6522C_status filed:", e)
            await asyncio.sleep_ms(1000) 

    def get_main_power_status(self):
        return self.power_status

    def turn_main_power(self):
        """
        turn ATX main power.
        """
        self.power_status = not self.power_status
        
        if self.power_status:
            self.power_ctl.value(1)
            print("main power opened.")
        else:
            self.power_ctl.value(0)
            print("main power closed.")
    
    
    